package com.android.lovingpet.util;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.ArrayRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Base64;
import android.util.Log;
import android.widget.Spinner;


import com.amap.api.location.AMapLocation;
import com.android.lovingpet.Application;
import com.android.lovingpet.R;
import com.android.lovingpet.bean.Account;
import com.android.lovingpet.bean.Team;
import com.android.lovingpet.common.Back;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by ikata on 2018/3/10.
 */

public class Utility {
    public synchronized static void setAccount(@NonNull Account account)
    {
        SharedPreferences.Editor editor= Application.getContext().getSharedPreferences("Account",Context.MODE_PRIVATE).edit();
        editor.putInt("realId",account.getRealId());
        editor.apply();
        account.saveOrUpdate();
    }
    @Nullable
    public synchronized static Account getAccount()
    {
        SharedPreferences sharedPreferences= Application.getContext().getSharedPreferences("Account", Context.MODE_PRIVATE);
        int realId= sharedPreferences.getInt("realId",1);
         List<Account> account= DataSupport.where("realId = ?",realId+"").limit(1).find(Account.class);
         if (account.isEmpty()) {
             Log.d("myLike account:","null");
             return null;
         }
        Log.d("myLike account:","存在");
        return account.get(0);
    }

    @Nullable
    public synchronized static Account getAccount( int realId)
    {
        List<Account> account= DataSupport.where("realId = ?",realId+"").limit(1).find(Account.class);
        if (account.isEmpty()) {
            Log.d("myLike account:","null");
            return null;
        }
        Log.d("myLike account:","存在");
        return account.get(0);
    }


   /* @Nullable
    public synchronized static Account getAccountByPhone()
    {
        SharedPreferences sharedPreferences= Application.getContext().getSharedPreferences("Account", Context.MODE_PRIVATE);
        String phone= sharedPreferences.getString("phone","");
        List<Account> account= DataSupport.where("phone=?",phone).limit(1).find(Account.class);
        if (account.size()==0)
            return null;
        else
        return account.get(0);
    }*/


    public synchronized static void setTeam(@NonNull Team team) {
        SharedPreferences.Editor editor= Application.getContext().getSharedPreferences("Team",Context.MODE_PRIVATE).edit();
        editor.putInt("realId",team.getRealId());
        editor.apply();
        team.saveOrUpdate();
    }

    public static Team getTeam() {
        SharedPreferences sharedPreferences= Application.getContext().getSharedPreferences("Team", Context.MODE_PRIVATE);
        int realId= sharedPreferences.getInt("realId",1);
        List<Team> teams= DataSupport.where("realId = ?",realId+"").limit(1).find(Team.class);
        if (teams.isEmpty())
            return null;
        return teams.get(0);
    }

    public static Team getTeam(int realId) {
        List<Team> teams= DataSupport.where("realId = ?",realId+"").limit(1).find(Team.class);
        if (teams.isEmpty())
            return null;
        return teams.get(0);
    }

    public static int getRealId()
    {
        SharedPreferences sharedPreferences= Application.getContext().getSharedPreferences("Account", Context.MODE_PRIVATE);
        int id= sharedPreferences.getInt("realId",1);
        return id;
    }
    public static void setRealId(int id)
    {
        SharedPreferences.Editor editor= Application.getContext().getSharedPreferences("Account",Context.MODE_PRIVATE).edit();
        editor.putInt("realId",id);
        editor.apply();
    }

    public static int getUserType()
    {
        SharedPreferences sharedPreferences= Application.getContext().getSharedPreferences("Account", Context.MODE_PRIVATE);
        int userType= sharedPreferences.getInt("userType",1);
        return userType;
    }
    public static void setUserType(int userType)
    {
        SharedPreferences.Editor editor= Application.getContext().getSharedPreferences("Account",Context.MODE_PRIVATE).edit();
        editor.putInt("userType",userType);
        editor.apply();
    }

    public static void clearSp()
    {
        SharedPreferences.Editor editor= Application.getContext().getSharedPreferences("Account",Context.MODE_PRIVATE).edit();
        editor.clear().commit();
    }

    public static String getJSessionId()
    {
        SharedPreferences sharedPreferences= Application.getContext().getSharedPreferences("Account", Context.MODE_PRIVATE);
        String sessionId= sharedPreferences.getString("sessionId","");
        return sessionId;
    }
    public static void setJSessionId(String sessionId)
    {
        SharedPreferences.Editor editor= Application.getContext().getSharedPreferences("Account",Context.MODE_PRIVATE).edit();
        editor.putString("sessionId",sessionId);
        editor.apply();
    }

    public static boolean isSaved(String... conditions)
    {
        boolean isSaved=true;
        List<Account> account= DataSupport.where(conditions).limit(1).find(Account.class);
        if (account.isEmpty())
        {
            isSaved=false;
        }
        return isSaved;
    }

    /*public static Account getInfo(String... conditions)
    {
        if (isSaved(conditions)==true) {
            List<Account> accounts=DataSupport.where(conditions).limit(1).find(Account.class);
            return accounts.get(0);
        }
        else
        {
             return null;
        }
    }*/

    //发广播来退出activity
    public static void exitActivity(Activity activity)
    {
        Intent intent=new Intent();
        intent.setAction("exitActivity");
        activity.sendBroadcast(intent);
        activity.finish();
    }
    public synchronized static List<Account> getAccounts(long...ids)
    {
        List<Account> accounts=new ArrayList<>();
        for (long id : ids) {
            Account account=getAccount((int)id);
            if (account!=null)
            {
                accounts.add(account);
            }
        }
        return accounts;
    }


    public static void openLocationPermission(Activity activity) {
        if (ActivityCompat.checkSelfPermission((Context)activity, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // Toast.makeText(getApplicationContext(),"没有权限,请手动开启定位权限",Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, 1);
        }
    }

    public static void addFragment(FragmentManager fm, int containerViewId, Fragment fragment) {
        fm.beginTransaction()
                .setCustomAnimations(
                        R.anim.slide_right_in,
                        R.anim.slide_left_out,
                        R.anim.slide_left_in,
                        R.anim.slide_right_out)
                .replace(containerViewId, fragment)
                .addToBackStack(null)
                .commit();
    }

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer,Base64.DEFAULT);
    }

    //手机存储卡是否挂载
    public static boolean hasSdcard()
    {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**匹配某个array的string
     * @param id array资源id
     * @param s 匹配的字符
     * @return
     */
    public static int matchArrayRes(@ArrayRes int id, String s)
    {
        String[] petType=Application.getContext().getResources().getStringArray(R.array.petType);
       for (int i=0;i<petType.length;i++)
       {
           if (petType[i].equals(s)){
               return i;
           }
       }
       return -1;
    }

}
